import axios from 'axios'
import qs from 'qs'
import { Notice, Button, Poptip, Tooltip } from 'view-design'
import config from './build-config'
import store from './store'
import { saveAs } from 'file-saver';

// const base = '/api/taiyi/'
const base = '/api/'
// const staticPath = '//misc.chaomeifan.com/skin';
const preFixPath = SYSTEM_CONFIG.staticPath || ''
const staticPath = '//misc.hzzcckj.cn/skin'
const $ajax = axios.create({
  baseURL: base,
  timeout: 20000
})

//request拦截器
$ajax.interceptors.request.use(function(config) {
  // let u = config.url.slice(4)
  // config.url = (config.url === '/api/ext_resource/config/tire_spec.js' || config.url === '/api/qrcode/wechat_qrcode') ? config.url : '/api' + u
  // if ( config.url === '/api/admin/tiger/area/list_by_parentId') {
  //   config.url = '/api/applet' + u
  // }
  //每次发送请求之前检测都vuex存有token,那么都要放在请求头发送给服务器
  let userToken = store.state.user.user.userToken
  config.headers['supplier-domain'] = 'xt'
  if(userToken){
    config.headers['Access-Token'] = `${userToken}`
  }
  return config
}, function(err) {
  return Promise.reject(err)
}
)
$ajax.interceptors.response.use(function(response) {
  let data = response.data
  if (data.code === 200) {
    return data.data
  } else if (data.code === 210 || data.code === -9015) {
    data.data = data.data || {}
    data.data.code = data.code
    return data.data
  } else if (data.code === 108 || data.code === 520001 || data.code === 520005 || data.code === 520006 || data.code === 520009 || data.code === 100009 || data.code === 100001) {
    let $router = window.app.$router
    let $route = window.app.$route
    let route = {
      name: 'login',
      query: $route.query
    }
    if ($route.name) route.query.name = $route.name
    $router.push(route)
    return Promise.reject()
  } else if (data.code === 520000 ) {
    let $router = window.app.$router
    let $route = window.app.$route
    let route = {
      name: 'refuse',
      query: $route.query
    }
    if ($route.name) route.query.name = $route.name
    $router.replace(route)
    return Promise.reject()
  } else if (data.code === 100013) {
    let $router = window.app.$router
    let $route = window.app.$route
    let route = {
      name: 'disabled',
      query: $route.query
    }
    if ($route.name) route.query.name = $route.name
    $router.replace(route)
  } else if (data.code === 101) {
    Notice.warning({
      title: '温馨提示',
      desc: data.message
    })
    let $router = window.app.$router
    let $route = window.app.$route
    let route = {
      name: 'setting/role/list',
      query: $route.query
    }
    if ($route.name) route.query.name = $route.name
    $router.push(route) 
  } else {
    if (data.message) {
      Notice.warning({
        title: '温馨提示',
        desc: data.message
      })
    } else {
      if (response.data && !data.code) {
        return response
      }
      Notice.error({
        title: '请求失败',
        desc: '未知错误'
      })
    }
    return Promise.reject(data)
  }
}, function(error) {
  if (error.request.status === 400) {
    let response = JSON.parse(error.request.response)
    let message = response.message
    if (message) {
      Notice.error({
        title: '温馨提示',
        desc: message
      })
    } else {
      Notice.error({
        title: '请求失败',
        desc: '未知错误'
      })
    }
  } else {
    Notice.error({
      title: '请求失败',
      desc: '错误代码：' + error.request.status
    })
  }
  return Promise.reject(error)
})
const ajaxPost = (api, data = null) => $ajax.post(api, qs.stringify(data, { arrayFormat: 'repeat' }))
const ajaxGet = (api, data = null) => $ajax.get(api, { 
  params: { ...data, '_': new Date().getTime() }, paramsSerializer: function(params) {
    return qs.stringify(params, { arrayFormat: 'repeat' })
  }
})
const jsonPost = (api, data = null) => $ajax.post(api, data, { headers: { 'Content-Type': 'application/json;charset=UTF-8' } })

const uploadImageUrl = '/api/user/uploadFile'
const uploadFlashUrl = '/api/taiyi/upload/FlASH'
const uploadMediaUrl = '/api/user/uploadFile'
const uploadFileUrl = '/api/user/uploadFile'   
const formatCurrency = (num, hasSymbol) => {
  if (!num) num = 0
  num = num.toString().replace(/\$|,/g, '')
  let sign = (num == (num = Math.abs(num)))
  num = Math.floor(num * 100 + 0.50000000001)
  let cents = num % 100
  num = Math.floor(num / 100).toString()
  if (cents < 10) { cents = '0' + cents }
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) { num = num.substring(0, num.length - (4 * i + 3)) + ',' +
    num.substring(num.length - (4 * i + 3)) }
  return ((hasSymbol ? '￥' : '') + ((sign) ? '' : '-') + num + '.' + cents)
}

const formatCurrencyNum = (num, hasSymbol) => {
  num = Number(num)
  if (!num) num = 0;
  if (num < 0.01 && num > 0) {
      num = 0.01
  }
  num = formatFloat(num, window.SYSTEM_CONFIG.priceScale || 2)
  if (hasSymbol) {
      return window.SYSTEM_CONFIG.currencySign + num
  } else {
      return Number(num)
  }
}

// 保留n位小数并格式化输出（不足的部分补0）
const formatFloat = (value, n = 2) => {
  var f = Math.round(value * Math.pow(10, n)) / Math.pow(10, n)
  var s = f.toString()
  var rs = s.indexOf('.')
  if (rs < 0) {
    s += '.'
  }
  for (let i = s.length - s.indexOf('.'); i <= n; i++) {
    s += '0'
  }
  return s
}

const download = (url, obj = {}, { clearEmpty } = { clearEmpty: true }) => {
  let $download = document.querySelector('#download')
  if ($download) {
    let list = Object.entries(obj).filter(item => !Array.isArray(item[1]))
    if (clearEmpty) {
      list = list.filter(item => {
        if (item[1] === null || item[1] === '') {
          return false
        } else {
          return true
        }
      })
    }
    let param = list.filter(item => item[1] !== undefined).map(item => `${item[0]}=${item[1]}`).join('&')
    let userToken = store.state.user.user.userToken
    let href = base + '/admin' + url + '?' + param + '&Authorization=Bearer ' + userToken
    $download.action = href
    $download.submit()
    console.log('下载文件 =》' + href)
  }
  return
}

// const formatCurrency = (num, hasSymbol) => {
//   num = Number(num)
//   if (!num) num = 0
//   if (num < 0.01 && num > 0) {
//     num = 0.01
//   }
//   // toFixed 银行家四舍五入 四舍六入五取偶
//   num = Number(num.toFixed(SYSTEM_CONFIG.priceScale)) || 0
//   if (hasSymbol) {
//     return SYSTEM_CONFIG.currencySign + num
//   } else {
//     return Number(num)
//   }
// }


const formatDate = (value, hasTime) => {
  if (!value) return ''
  if (typeof value === 'string') {
    value = value.replace(/-/g, '/')
  }
  value = new Date(value)
  let result = ''
  let year = value.getFullYear()
  let month = value.getMonth() + 1
  let day = value.getDate()

  month = plusZero(month)
  day = plusZero(day)

  result = year + '-' + month + '-' + day

  if (hasTime) {
    let hour = value.getHours()
    let minute = value.getMinutes()
    let seconds = value.getSeconds()
    hour = plusZero(hour)
    minute = plusZero(minute)
    seconds = plusZero(seconds)
    result += ' ' + hour + ':' + minute + ':' + seconds
  }

  return result
}

const formatMonth = (value) => {
  if (!value) return ''
  if (typeof value === 'string') {
    value = value.replace(/-/g, '/')
  }
  value = new Date(value)
  let result = ''
  let year = value.getFullYear()
  let month = value.getMonth() + 1

  month = plusZero(month)

  result = year + '-' + month

  return result
}

const formatOnlyMonth = (value) => {
  if (!value) return ''
  if (typeof value === 'string') {
    value = value.replace(/-/g, '/')
  }
  value = new Date(value)
  let result = ''
  let month = value.getMonth() + 1

  month = plusZero(month)

  result = month

  return result
}

const formatOnlyYear = (value) => {
  if (!value) return ''
  if (typeof value === 'string') {
    value = value.replace(/-/g, '/')
  }
  value = new Date(value)
  let result = ''
  let year = value.getFullYear()

  result = year
  return result
}

const formatTime = (value) => {
  if (!value) return ''
  if (typeof value === 'string') {
    value = value.replace(/-/g, '/')
  }
  value = new Date(value)

  let result = ''
  let hour = value.getHours()
  let minute = value.getMinutes()
  hour = plusZero(hour)
  minute = plusZero(minute)
  result += ' ' + hour + ':' + minute

  return result
}

const plusZero = (value) => {
  return value < 10 ? '0' + value : value
}

const getOriginData = (data) => {
  return JSON.parse(JSON.stringify(data))
}

const isIE = function() {
  let userAgent = navigator.userAgent //取得浏览器的userAgent字符串 
  return userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && userAgent.indexOf('Opera') === -1
}

const escapeHtml = function(html) {
  return html.replace(/</g, '&lt;').replace(/>/g, '&gt;')
}

const parseHtml = function(html) {
  return html.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
}

const getRandom = (min = 0, max = 1) => {
  return Math.round(Math.random() * (max - min) + min)
}
const clearEmpty = (obj) => {
  let param = {
    ...obj
  }
  for (let key in param) {
    if (param[key] === '' || param[key] === null) {
      delete param[key]
    }
  }
  return param
}
const guid = function() {  
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {  
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)  
    return v.toString(16)  
  })  
}
/**
 * 
 * @param {渲染函数} h 
 * @param { disabled, type, text, confirm  } params // 是否禁用，按钮类型，按钮文本，删除确认
 * @param { ()=>{} } fn  // 点击触发的回调函数，
 */
const renderButton = function(h,params,fn) {
  let cb = () => { fn && fn() }
  let btn = (cb) => {
    return (
      <Button size='small' class='ml5'
        disabled={params.disabled}
        onClick={ cb }
        type={params.type?params.type:'default'}>
          {params.text}
      </Button>
    )
  }
  let btnWithCfm = (cb) => {
    return (
      <Poptip
        confirm
        transfer
        title="确定删除吗?"
        onOn-ok={cb}>
        {btn()}
      </Poptip>
    )
  }
  if (params.confirm) {
    return btnWithCfm(cb)
  }
  return btn(cb)
}
const renderText = function (h, text) {
    let tooltip = <Tooltip transfer content={text} class="table-cell-tool" max-width="300" placement="bottom-start">
            <span class="ivu-table-cell-tooltip-content">{text}</span>
        </Tooltip>
    return tooltip
}
// 函数防抖
 const debounce = function(fn, delay, immediate) {
  let timer = null;
  return function() {
      const context = this;
      const args = arguments;
      return new Promise((resolve, reject) => {
        timer && clearTimeout(timer);
        if (immediate) {
          const doNow = !timer;
          timer = setTimeout(() => {
              timer = null;
          }, delay);
          doNow && resolve(fn.apply(context, args));
        }
        else {
          timer = setTimeout(() => {
              resolve(fn.apply(context, args));
          }, delay);
        }
    });
  };
}
//公共尺寸
const getTireArr = function(url = '//misc.hzzcckj.cn/config/tire_spec.js') {
  return new Promise (resolve => {
    let xhr = new XMLHttpRequest()
    xhr.open('get', url, true)
    xhr.onload = function() {
      if (xhr.status === 200) {
        resolve(JSON.parse(xhr.responseText))
      }
    }
    xhr.send(null)
  })
}

const comparativeDate = function(date1,date2){
  let oDate1 = new Date(date1)
  let oDate2 = new Date(date2)
  return oDate1.getTime() > oDate2.getTime() ? true : false
}
// 文件流下载
const downloadFileStream = function(url, params) {
  return new Promise((resolve, reject) => {
    ajaxGet(url, params, { responseType: 'blob' }).then(res => {
      let name = ''
      if (res.headers['content-disposition']) {
        let content = res.headers['content-disposition']
        let name1 = content.split('filename=')[1]; // 获取filename的值
        name = decodeURIComponent(name1);
      }
      if (res.data.type === 'application/json') {
        var reader = new FileReader();
        reader.readAsText(res.data, 'utf-8');
        reader.onload = function () {
          let data = JSON.parse(reader.result);
          Notice.error({
            title: data.message,
          })
          reject()
        }
      } else {
        // 移除name字符串前后双引号
        // var fileDownload = require("js-file-download");
        // fileDownload(res.data, name);
        let blob = new Blob([res.data], {type: "application/zip"}); 
        　　let objectUrl = URL.createObjectURL(blob); 
        　　 window.location.href = objectUrl; 
        // window.location.href = res.data
        // downloadFile(res.data,res.data.type,name.replace(/^\"|\"$/g, ''))
        // saveAs(res.data,res.data.type, name.replace(/^\"|\"$/g, ''))
        resolve()
      }
    })
  })
}

// 文件流转blob对象下载
function downloadFile(data, type, fileName) {
  let blob = new Blob([data], {type: `application/${type};charset=utf-8`});
  // 获取heads中的filename文件名
  let downloadElement = document.createElement('a');
  // 创建下载的链接
  let href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  // 下载后文件名
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  // 点击下载
  downloadElement.click();
  // 下载完成移除元素
  document.body.removeChild(downloadElement);
  // 释放掉blob对象
  window.URL.revokeObjectURL(href);

}
const telReg = /^[1]\d{10}$/
const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
const plateReg = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{4,7}[\u4e00-\u9fa5]?$/
const emailReg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
try {
  window.console && console.info && console.info('  _______    _       _ \n |__   __|  (_)     (_)\n    | | __ _ _ _   _ _ \n    | |/ _` | | | | | |\n    | | (_| | | |_| | |\n    |_|\__,_|_|\__, |_|\n                __/ |  \n               |___/   ')
  window.console && console.info && console.info('version:' + config.verssion)
} catch (c) {
  console.log(c)
}
const getQueryString = function (url, name) {
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
    return r[2]
  }
  return null
}
export {
  base,
  staticPath,
  preFixPath,
  $ajax,
  ajaxGet,
  ajaxPost,
  jsonPost,
  download,
  formatCurrency,
  formatCurrencyNum,
  formatDate,
  formatFloat,
  formatTime,
  getOriginData,
  isIE,
  escapeHtml,
  parseHtml,
  getRandom,
  telReg,
  idCardReg,
  plateReg,
  emailReg,
  uploadImageUrl,
  uploadFlashUrl,
  uploadMediaUrl,
  uploadFileUrl,
  formatMonth,
  formatOnlyMonth,
  formatOnlyYear,
  clearEmpty,
  guid,
  renderButton,
  debounce,
  getTireArr,
  comparativeDate,
  getQueryString,
  renderText,
  downloadFileStream
}
